package cn.news.upload.action;

import java.io.IOException;
import java.sql.Timestamp;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;

import cn.news.upload.entities.OperResult;
import cn.news.upload.entities.XhUploadInfo;
import cn.news.upload.service.InfoService;
import cn.news.upload.service.VideoUploadService;
import cn.news.upload.utils.JasonUtils;

/**
 * Created by dell on 2016/11/15.
 */
@RequestMapping("video")
@Controller
public class VideoUploadAction {

	private static final Logger LOGGER = LoggerFactory.getLogger(VideoUploadAction.class);

	@Autowired
	private VideoUploadService vusv;

	@Autowired
	private InfoService infosv;

	/**
	 * @param videoFile
	 *            MultipartFile类型的文件对象
	 * @param createUser
	 *            用户
	 * @param appId
	 *            应用id
	 * @param resourceType
	 *            资源类型
	 * @param request
	 * @param response
	 * @return jsonObject形如： { code: 200, 200:视频库响应正常; 500:视频库响应失败; 0:上传异常
	 *         content: { // 初次上传完成，会包含 "pieceNum":5, "videoId":9215 //
	 *         已经上传过并转码完成，会包含各种路径信息，及"videoId":9217, "exist":1, "pieceSum":5,
	 *         "videoTime":278, "resourceType":"S", "status":1 //
	 *         已经上传过但仍然在转码，则只有 videoId, exist, pieceSum, videoTime,
	 *         resourceType, status字段，无路径信息 } }
	 * @throws IOException
	 */
	@RequestMapping(value = "upload", method = RequestMethod.POST)
	public String uploadMobileVideo(XhUploadInfo info, @RequestParam MultipartFile videoFile,
			@RequestParam(value = "appId") String appId, @RequestParam(value = "resourceType") String resourceType, @RequestParam String v1,
			@RequestParam String v2, HttpServletRequest request, HttpServletResponse response) throws IOException {
		OperResult or = new OperResult();
		String referer = request.getHeader("referer");

		if(null == info){
			or.setCode(OperResult.CODE_FAIL);
			or.setMessage("info is null");
			JasonUtils.writeJasonP(request, response, or);
			return "redirect:" + v2;
		}
		
		info.setCreateTime(new Timestamp(System.currentTimeMillis()));
		
		try {
			OperResult orc = infosv.checkApp(info, referer);
			if (orc.getCode() == OperResult.CODE_FAIL) {
				JSONObject.toJSONString(orc);
				LOGGER.debug("CHECK : app not correct orc=" + orc);
				return "redirect:" + v2;
			}


			JSONObject resultObj = vusv.uploadMobileVideo(videoFile, info.getUserName(), appId, resourceType);
			LOGGER.info("UPLOAD_RESULT : " + resultObj);
			
			JSONObject contentObj = resultObj.getJSONObject("content");
			if(null == resultObj || null == contentObj){
				or.setCode(OperResult.CODE_FAIL);
				or.setMessage("result or result content is null");
				JasonUtils.writeJasonP(request, response, or);
				return "redirect:" + v2;
			}
			
			String fileName = resultObj.getString("fileName");
			String convertMp4Path = contentObj.getString("convertMp4Path");
			String convertFlvPath = contentObj.getString("convertFlvPath");
			String surfacePicUrl = contentObj.getString("surfacePicUrl");
			
			while(StringUtils.isEmpty(convertMp4Path)){
				Thread.sleep(10 * 1000);
				
				JSONObject judgeObj = vusv.judgeVideoMd5(videoFile, info.getUserName(), appId, resourceType);
				JSONObject judgeContent = judgeObj.getJSONObject("content");
				convertMp4Path = judgeContent.getString("convertMp4Path");
				convertFlvPath = judgeContent.getString("convertFlvPath");
				surfacePicUrl = judgeContent.getString("surfacePicUrl");
				LOGGER.info("JUDGE_RESULT : " + judgeObj);
			}
			
			info.setVideo_fileName(fileName);
			info.setVideo_surfacePicUrl(surfacePicUrl);
			info.setVideo_mp4Url(convertMp4Path);
			info.setVideo_flvUrl(convertFlvPath);
			infosv.addInfo(info);
		} catch (Exception e) {
			LOGGER.error("video upload exception", e);
			or.setCode(OperResult.CODE_FAIL);
			or.setMessage("video upload fail, " + e.getMessage());
			JSONObject.toJSONString(or);
			return "redirect:" + v2;
		}

		return "redirect:" + v1;
	}
}